//
//  UIColorExtension.swift
//  multimeter
//
//  Created by 强建龙 on 17/7/27.
//  Copyright © 2017年 chinake. All rights reserved.
//

import UIKit

extension UIColor {
    
    static func colorWithRGBA(_ r: Int, _ g: Int, _ b: Int, _ a: Int = 255) -> UIColor {
        let red = CGFloat(Float(r) / 255.0)
        let green = CGFloat(Float(g) / 255.0)
        let blue = CGFloat(Float(b) / 255.0)
        let alpha = CGFloat(Float(a) / 255.0)
        return UIColor(red: red, green: green, blue: blue, alpha: alpha)
    }
    
    static func colorWithHex(_ hex: Int) -> UIColor {
        let r: Int = (hex & 0xFF0000) >> 16
        let g: Int = (hex & 0x00FF00) >> 8
        let b: Int = (hex & 0x0000FF)
        return colorWithRGBA(r, g, b)
    }
    
    static func colorFromRGB(_ hex:String) -> UIColor {
        var cString:String = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
        
        if (cString.hasPrefix("#")) {
            cString = (cString as NSString).substring(from: 1)
        }
        let rString = (cString as NSString).substring(to: 2)
        let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2)
        let bString = ((cString as NSString).substring(from: 4) as NSString).substring(to: 2)
        
        var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
        Scanner(string: rString).scanHexInt32(&r)
        Scanner(string: gString).scanHexInt32(&g)
        Scanner(string: bString).scanHexInt32(&b)
        return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
    }
}
